import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_app/models/community.dart';
import 'package:flutter_app/utils/dio_http.dart';
import 'package:flutter_app/utils/scoped_model_helper.dart';
import 'package:flutter_app/widgets/search_bar.dart';

class CommunityPage extends StatefulWidget {
  const CommunityPage({Key? key}) : super(key: key);

  @override
  _CommunityPageState createState() => _CommunityPageState();
}

class _CommunityPageState extends State<CommunityPage> {
  List<Community> dataList = [];
  _searchSubmit(String value) async {
    var areaId = ScopedHelperModel.getAreaId(context);
    var res =
        await DioHttp.of(context).get('/area/community?name=$value&id=$areaId');
    var resString = json.decode(res.toString())["body"];
    List<Community> resList =
        List<Community>.from(resString.map((i) => Community.fromJson(i)));
    setState(() {
      dataList = resList;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: SearchBar(
            onTabSearch: () {},
            goBack: true,
            cancel: () {
              Navigator.of(context).pop();
            },
            searchSubmit: _searchSubmit),
        backgroundColor: Colors.white,
        elevation: 0,
      ),
      body: ListView.separated(
          itemBuilder: (context, index) {
            return GestureDetector(
              behavior: HitTestBehavior.translucent,
              child: Container(
                padding: const EdgeInsets.all(10.0),
                child: Text(dataList[index].name),
              ),
              onTap: () {
                Navigator.of(context).pop(dataList[index]);
              },
            );
          },
          separatorBuilder: (BuildContext context, int index) =>
              const Divider(),
          itemCount: dataList.length),
    );
  }
}
